package qingxin.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import qingxin.dao.TokenDAO;
import qingxin.dbc.DatabaseConnection;

public class TokenDAOImpl implements TokenDAO {

	@Override
	public String[] getAll() throws Exception{
		ArrayList<String> tokens = new ArrayList<String>();
		String sql = "select token from token";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			ResultSet rs = pstmt.executeQuery();
			
			while(rs.next()){
				tokens.add(rs.getString(1));
			}
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		
		return tokens.toArray(new String[0]);
	}

	@Override
	public void add(String token) throws Exception {
		String sql = "insert into token (token) values (?)";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setString(1, token);
			
			pstmt.executeUpdate();
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
	}

	@Override
	public boolean isExist(String token) throws Exception {
		boolean exist = false;
		String sql = "select * from token where token=?";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setString(1, token);
			
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				exist = true;
			}
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		return exist;
	}

}
